package rpc05;


import com.hl.rpc.common.User;
import com.hl.rpc.service.IUserService;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by yuanhailong on 2021/10/30.
 */
public class Server {

    private static boolean running=true;

    public static void main(String[] args) throws Exception{

        ServerSocket serverSocket=new ServerSocket(9999);

        System.out.println("rpc05 服务端启动...");
        while (running){
            Socket socket=serverSocket.accept();
            process(socket);
            socket.close();
        }
        serverSocket.close();
    }


    private static void process(Socket socket) throws Exception{
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

        String className = ois.readUTF();
        String methodName = ois.readUTF();
        Class[] paramTypes=(Class[])ois.readObject();
        Object[] args=(Object[])ois.readObject();
        System.out.println("服务端调用方法的方法名:"+methodName);
        System.out.println("服务端调用类名:"+className);

        //可以从服务注册表中查找
        Class clazz=UserServiceImp.class;

        Method method = clazz.getMethod(methodName, paramTypes);
        User user = (User)method.invoke(clazz.newInstance(), args);
        oos.writeObject(user);
        oos.flush();
    }
}
